package com.pwc.conversionTool.soapUtil.thread;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.appengine.api.ThreadManager;
import com.pwc.conversionTool.entity.Account;

public class ThreadPool {

	
	private static ThreadPool singleInstance=null;
	
	private  List<SoapThread> threads = new  ArrayList<SoapThread>();
	
	private static final int maxSize=10;//GAE just support 10 thread
	

	public void stopTask(String taskName) {

	}
	
	
	
	private ThreadPool() {
		super();
	}

	
	public static ThreadPool getInstance(){
		
		if(singleInstance==null)
		{
			singleInstance=new ThreadPool();
		}
		
		return singleInstance;
	}
	
	

	public boolean addThread(SoapThread process) {
		
		if(isAvailable())
		{
			Thread thread= ThreadManager.createBackgroundThread(process);			
			thread.start();//max 10
			
			threads.add(process);			
			
			return true;
		}else {
			return false;
		}
		
	}
	
	
	
	

	
	
	public List<SoapThread> getThread(Account account) {
		cleanPool();
		
		List<SoapThread> resultList=new ArrayList<SoapThread>();
		
		for (SoapThread soapThread : threads) {
			if(soapThread.getAccount().equals(account))
			{
				resultList.add(soapThread);
			}
		}
		
		
		return resultList;
	}
	
	
	private void cleanPool()
	{
		List<SoapThread> removeList=new ArrayList<SoapThread>();
		
		for (SoapThread soapThread : threads) {
			if(!soapThread.isRunning()){
				removeList.add(soapThread);
			}
		}
		
		for(SoapThread soapThread : removeList)
		{
			threads.remove(soapThread);
		}		
		
	}
	
	
	
	
	public boolean isAvailable(){
		cleanPool();
		if(threads.size()<maxSize)
		{
			return true;
		}else {
			return false;
		}
	}
	
	

}
